import os
import xlsxwriter as xlsxwriter
from flask import Blueprint, request, make_response, jsonify
from flask import current_app as app
from io import BytesIO
from xlrd import open_workbook
from urllib.parse import quote
import datetime
import mimetypes

from utils.comm import get_data
from db import db1
from utils.myfile import myf

bp_company = Blueprint('company', __name__)


# @bp_company.route('/company')
# async def company():
#     str = "请求ip:" + request.remote_addr + "请求地址" + request.url + "错误信息"
#     app.logger.error(str)
#     return 'ok'

@bp_company.route('/upload', methods=['POST'])
def upload():
    # 获取文件
    print('aaaaa')
    file = request.files['file']
    print(file)
    newname = myf.rename(file.filename)
    # 上传文件
    file.save(os.path.join('./static/files/' + newname))
    # # 打开文件读取
    newname = '5a4cd6a47e844cea948cb80bf47cb119.xls'
    name = './static/files/' + newname
    # 封装数据写入数据库
    # bk = open_workbook(name, encoding_override='utf-8')
    # sh = bk.sheets()[0]
    # nrows = sh.nrows
    # print(nrows)
    # ncols = sh.ncols
    # print(ncols)
    # for i in range(2, nrows):
    #     row_date = sh.row_values(i)
    #     for j in range(0, ncols):
    #         print(row_date[j])
    return 'ok'


@bp_company.route('/download', methods=["GET", "POST"])
def download():
    # 实例化二进制数据
    out = BytesIO()
    # 创建一个Excel实例
    workbook = xlsxwriter.Workbook(out)
    # 添加一个sheet，add_worksheet()，默认"Sheet1"，可自定义命名，add_worksheet("资产列表")
    table = workbook.add_worksheet()
    # table.write(行, 列, 字段名)
    # 行、列从 0 开始计数
    # 字段命名根据每个人使用情况而定，插入数据部分也是

    workbook.close()
    filename = quote("资产列表_{}.xlsx".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
    file = make_response(out.getvalue())
    out.close()
    mime_type = mimetypes.guess_type('%s.xlsx' % filename)[0]
    file.headers['Content-Type'] = mime_type
    file.headers["Cache-Control"] = "no-cache"
    file.headers['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(filename)
    return file

#  无限极分类数据重构展示
def xtree(data):
    if not data:
        return data
    #  先把列表重组成字典
    dict1 = {}
    list1 = []
    for i in data:
        dict1[i['id']] = i

    for j in data:
        pid = j['pid']
        #  pid等于0，就是顶级，
        if pid == 0:
            # 直接加入列表
            list1.append(j)
        else:
            #  查看父类是否有子类
            if 'son' not in dict1[pid]:
                dict1[pid]['son'] = []
            dict1[pid]['son'].append(j)
    return list1


@bp_company.route('/zuzhi', methods=['GET','POST'])
def zuzhi():
    if request.method == 'POST':
        data = get_data()

        sql1 = "insert into company(name,pid,code,sort) values('{}',{},'{}',{})".format(data['name'],int(data['status']),data['code'])
        db1.update(sql1)
        return jsonify({'code': 200})
    else:
        sql = 'select * from company'
        res = db1.findall(sql)
        list1 = xtree(res)
        return jsonify({'code': 200, 'list': list1})
